﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Data;
using DAL.Entity;
using DAL.Persistencia;
using BLL.Utils;
using NewTierra.App_Code;

namespace NewTierra.Pages.MontarServicos
{
    public partial class MontarServicoConsulta : BasePage
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if ((base.ObterPerfilLogado() == (int)PerfilUsuario.Financeiro) || base.ObterPerfilLogado() == (int)PerfilUsuario.Operacional)
                btnSalvarTarifas.Enabled = false;

            if (!IsPostBack)
            {
                popularDrops();                
            }
        }

        #region Popular Dados

        protected void popularDrops()
        {
            PopulaDropMercadoFiltroBase();
            PopulaDropBaseTarifariaFiltroBase();
            PopulaDropMoedaFiltroBase();
            //popularDropTipoTransporteFiltroBase();
            popularDropTipoBaseFiltroBase();
            popularDropItemSubServico();
            popularDropSubItem();
            popularDropFiltroItemSubServico();
            popularDropFiltroSubItem();
        }

        protected void popularDropItemSubServico()
        {
            try
            {
                ItemSubServicoDAL isd = new ItemSubServicoDAL();

                ddlItemSubServico.DataSource = isd.ListarTodos();
                ddlItemSubServico.DataTextField = "ItemSubServico_nome";
                ddlItemSubServico.DataValueField = "ItemSubServico_id";
                ddlItemSubServico.DataBind();

                ddlItemSubServico.Items.Insert(0, new ListItem("Selecione...", "0"));
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void popularDropSubItem()
        {
            try
            {
                SubItemDAL sbd = new SubItemDAL();

                ddlSubItemSubServico.DataSource = sbd.ListarTodos();
                ddlSubItemSubServico.DataTextField = "SubItem_nome";
                ddlSubItemSubServico.DataValueField = "SubItem_id";
                ddlSubItemSubServico.DataBind();

                ddlSubItemSubServico.Items.Insert(0, new ListItem("Selecione...", "0"));
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void popularDropFiltroItemSubServico()
        {
            try
            {
                ItemSubServicoDAL isd = new ItemSubServicoDAL();

                ddlFiltroMServicoItemSubServico.DataSource = isd.ListarTodos();
                ddlFiltroMServicoItemSubServico.DataTextField = "ItemSubServico_nome";
                ddlFiltroMServicoItemSubServico.DataValueField = "ItemSubServico_id";
                ddlFiltroMServicoItemSubServico.DataBind();

                ddlFiltroMServicoItemSubServico.Items.Insert(0, new ListItem("Selecione...", "0"));
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void popularDropFiltroSubItem()
        {
            try
            {
                SubItemDAL sbd = new SubItemDAL();

                ddlFiltroMServicoSubItem.DataSource = sbd.ListarTodos();
                ddlFiltroMServicoSubItem.DataTextField = "SubItem_nome";
                ddlFiltroMServicoSubItem.DataValueField = "SubItem_id";
                ddlFiltroMServicoSubItem.DataBind();

                ddlFiltroMServicoSubItem.Items.Insert(0, new ListItem("Selecione...", "0"));
            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void PopulaDropMercadoFiltroBase()
        {
            try
            {
                using (NewTierraEntities n = new NewTierraEntities())
                {
                    ddlMercadoFiltro_Base.DataSource = n.Mercadoes.ToList();
                    ddlMercadoFiltro_Base.DataValueField = "Mercado_id";
                    ddlMercadoFiltro_Base.DataTextField = "Mercado_nome";
                    ddlMercadoFiltro_Base.DataBind();
                }
            }
            catch (Exception ex)
            {
                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        protected void PopulaDropBaseTarifariaFiltroBase()
        {
            try
            {
                using (NewTierraEntities n = new NewTierraEntities())
                {
                    ddlBaseTarifariaFiltro_Base.DataSource = n.BaseTarifarias.ToList();
                    ddlBaseTarifariaFiltro_Base.DataValueField = "BaseTarifaria_id";
                    ddlBaseTarifariaFiltro_Base.DataTextField = "BaseTarifaria_nome";
                    ddlBaseTarifariaFiltro_Base.DataBind();
                }
            }
            catch (Exception ex)
            {
                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        protected void PopulaDropMoedaFiltroBase()
        {
            try
            {
                using (NewTierraEntities Con = new NewTierraEntities())
                {
                    ddlMoedaFiltro_Base.DataSource = Con.Moeda.ToList();
                    ddlMoedaFiltro_Base.DataTextField = "Moeda_sigla";
                    ddlMoedaFiltro_Base.DataValueField = "Moeda_id";
                    ddlMoedaFiltro_Base.DataBind();
                }

            }
            catch (Exception ex)
            {
                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        protected void popularDropTipoBaseFiltroBase()
        {
            try
            {
                using (NewTierraEntities Con = new NewTierraEntities())
                {
                    ddlTipoBase_Base.DataSource = Con.Tipo_Base.OrderBy(t => t.TipoBase_nome).ToList();
                    ddlTipoBase_Base.DataTextField = "TipoBase_nome";
                    ddlTipoBase_Base.DataValueField = "TipoBase_id";
                    ddlTipoBase_Base.DataBind();

                    ddlTipoBase_Base.SelectedValue = "2";

                    //ddlTipoTransporte.Items.Insert(0, new ListItem("Selecione...", "0"));
                }
            }
            catch (Exception ex)
            {
                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        protected void PopulaDataListBases(int index)
        {
            try
            {
                SBasesDAL b = new SBasesDAL();
                SupplierDAL s = new SupplierDAL();
                MontaServicoDAL ms = new MontaServicoDAL();

                Supplier sp = s.ObterSupplierPorNome(txtSupplier.Text);
                ViewState["IdSupplier"] = sp.S_id;

                if (b.ListarTodosPorSupplier(sp.S_id, index, Convert.ToInt32(ddlMercadoFiltro_Base.SelectedValue), Convert.ToInt32(ddlBaseTarifariaFiltro_Base.SelectedValue), Convert.ToInt32(ddlMoedaFiltro_Base.SelectedValue), Convert.ToInt32(ddlTipoBase_Base.SelectedValue)).Count() == 0)
                {
                    MostrarMsg("Não existe bases cadastradas para este supplier.");
                    btnSalvarTarifas.Visible = false;
                }
                else
                {
                    btnSalvarTarifas.Visible = true;
                    rdoBasesIndex.SelectedValue = index.ToString();
                    lblMsgCadMServicos.Text = "";
                }


                DataListBases.DataSource = b.ListarTodosPorSupplier(sp.S_id, index, Convert.ToInt32(ddlMercadoFiltro_Base.SelectedValue), Convert.ToInt32(ddlBaseTarifariaFiltro_Base.SelectedValue), Convert.ToInt32(ddlMoedaFiltro_Base.SelectedValue), Convert.ToInt32(ddlTipoBase_Base.SelectedValue));
                DataListBases.DataBind();

                if (!txtCodMServico.Text.Equals(""))
                {
                    PopulaIntoDataList(DataListBases);
                }



                //if (b.ListarTodosPorSupplier(sp.S_id, 2, Convert.ToInt32(ddlMercadoFiltro_Base.SelectedValue), Convert.ToInt32(ddlBaseTarifariaFiltro_Base.SelectedValue), Convert.ToInt32(ddlMoedaFiltro_Base.SelectedValue), Convert.ToInt32(ddlTipoTransporte.SelectedValue), Convert.ToInt32(ddlTipoBase_Base.SelectedValue)).Count() > 0)
                //{
                //    lblBases2TXT.Visible = true;
                //    DataListBases2.DataSource = b.ListarTodosPorSupplier(sp.S_id, 2, Convert.ToInt32(ddlMercadoFiltro_Base.SelectedValue), Convert.ToInt32(ddlBaseTarifariaFiltro_Base.SelectedValue), Convert.ToInt32(ddlMoedaFiltro_Base.SelectedValue), Convert.ToInt32(ddlTipoTransporte.SelectedValue), Convert.ToInt32(ddlTipoBase_Base.SelectedValue));
                //    DataListBases2.DataBind();

                //    if (!txtCodMServico.Text.Equals(""))
                //    {
                //        PopulaIntoDataList(DataListBases2);
                //    }
                //}
                //else
                //{
                //    DataListBases2.DataSource = b.ListarTodosPorSupplier(sp.S_id, 2, Convert.ToInt32(ddlMercadoFiltro_Base.SelectedValue), Convert.ToInt32(ddlBaseTarifariaFiltro_Base.SelectedValue), Convert.ToInt32(ddlMoedaFiltro_Base.SelectedValue), Convert.ToInt32(ddlTipoTransporte.SelectedValue), Convert.ToInt32(ddlTipoBase_Base.SelectedValue));
                //    DataListBases2.DataBind();
                //    lblBases2TXT.Visible = false;
                //}


                //if (b.ListarTodosPorSupplier(sp.S_id, 3, Convert.ToInt32(ddlMercadoFiltro_Base.SelectedValue), Convert.ToInt32(ddlBaseTarifariaFiltro_Base.SelectedValue), Convert.ToInt32(ddlMoedaFiltro_Base.SelectedValue), Convert.ToInt32(ddlTipoTransporte.SelectedValue), Convert.ToInt32(ddlTipoBase_Base.SelectedValue)).Count() > 0)
                //{
                //    lblBases3TXT.Visible = true;
                //    DataListBases3.DataSource = b.ListarTodosPorSupplier(sp.S_id, 3, Convert.ToInt32(ddlMercadoFiltro_Base.SelectedValue), Convert.ToInt32(ddlBaseTarifariaFiltro_Base.SelectedValue), Convert.ToInt32(ddlMoedaFiltro_Base.SelectedValue), Convert.ToInt32(ddlTipoTransporte.SelectedValue), Convert.ToInt32(ddlTipoBase_Base.SelectedValue));
                //    DataListBases3.DataBind();

                //    if (!txtCodMServico.Text.Equals(""))
                //    {
                //        PopulaIntoDataList(DataListBases3);
                //    }
                //}
                //else
                //{
                //    DataListBases3.DataSource = b.ListarTodosPorSupplier(sp.S_id, 3, Convert.ToInt32(ddlMercadoFiltro_Base.SelectedValue), Convert.ToInt32(ddlBaseTarifariaFiltro_Base.SelectedValue), Convert.ToInt32(ddlMoedaFiltro_Base.SelectedValue), Convert.ToInt32(ddlTipoTransporte.SelectedValue), Convert.ToInt32(ddlTipoBase_Base.SelectedValue));
                //    DataListBases3.DataBind();
                //    lblBases3TXT.Visible = false;
                //}

            }
            catch (Exception ex)
            {
                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        protected void PopulaIntoDataList(DataList nome)
        {
            try
            {
                MontaServicoValoresDAL msv = new MontaServicoValoresDAL();

                List<Monta_Servico_Valores> listaValores = msv.ListaTodos(Convert.ToInt32(txtCodMServico.Text));


                foreach (DataListItem item in nome.Items)
                {
                    TextBox txtValoresBases = (TextBox)item.FindControl("txtValoresBases");
                    Label baseID = (Label)item.FindControl("baseID");
                    Label lblTotalBulk = (Label)item.FindControl("lblTotalBulk");
                    Label lblIDValores = (Label)item.FindControl("lblIDValores");

                    foreach (Monta_Servico_Valores lista in listaValores)
                    {
                        if (lista.Base_id == Convert.ToInt32(baseID.Text))
                        {
                            txtValoresBases.Text = Convert.ToString(lista.MServico_Valores_Bulk);
                            lblTotalBulk.Text = Convert.ToString(lista.MServico_Valores_Bulk_Total);
                            lblIDValores.Text = Convert.ToString(lista.IdMServicoValores);
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        protected void PopulaGridMServicos()
        {
            try
            {
                MontaServicoDAL ms = new MontaServicoDAL();

                GridMServicos.DataSource = ms.ListarTodosCondicaoMSCustos(Convert.ToInt32(ViewState["IdSupplier"]));
                GridMServicos.DataBind();

            }
            catch (Exception ex)
            {
                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        #endregion

        #region CRUD Montar Servico

        protected void SalvarTarifas(object sender, EventArgs e)
        {
            try
            {

                if (txtCodMServico.Text != "")
                {
                    lblMsgCadMServicos.Text = "";
                    btnSalvarTarifas.Text = "Salvar";
                    //PanelDataLists.Visible = false;                    
                    //txtSupplier.Focus();
                    //LimpaCampos(this.Controls);
                    from.Text = "";
                    to.Text = "";
                    txtCodMServico.Text = "";
                    rdoBasesIndex.SelectedValue = "1";
                    PopulaDataListBases(1);
                    //popularDropItemSubServico();
                    //popularDropSubItem();                    
                    txtPorcentagemTaxa.Text = "0";
                    txtPorcentagemImposto1.Text = "0";
                    txtComissao.Text = "0";
                    btnAtualizarTarifas.Visible = false;
                    //PopulaGridMServicos();
                    return;
                }

                txtPorcentagemTaxa_TextChanged(sender, e);
                txtPorcentagemComissao_TextChanged(sender, e);

                Utils u = new Utils();
                MontaServicoDAL msd = new MontaServicoDAL();

                if (msd.VerificaMS(Convert.ToInt32(ViewState["IdSupplier"]),
                    Convert.ToInt32(ddlItemSubServico.SelectedValue),
                    Convert.ToInt32(ddlSubItemSubServico.SelectedValue)))
                {
                    MostrarMsg("Já existem tarifas cadastradas com esses parâmetros(Transporte, Servico e Serviço Categoria).");
                    return;
                }

                if (ddlItemSubServico.SelectedValue.Equals("0"))
                { MostrarMsg("Favor selecione um item subserviço."); return; }
                if (ddlSubItemSubServico.SelectedValue.Equals("0"))
                { MostrarMsg("Favor selecione um sub item."); return; }

                foreach (DataListItem item in DataListBases.Items)
                {
                    TextBox txtValoresBases = (TextBox)item.FindControl("txtValoresBases");
                    string Bulk = txtValoresBases.Text;

                    if (!u.ValidaNumeroComVirgula(Bulk))
                    {
                        MostrarMsg("Favor digite somente números nas tarifas.");
                        return;
                    }
                }

                Monta_Servico ms = new Monta_Servico();

                ms.MServico_Bulk_Porc_Taxa = Convert.ToDecimal(txtPorcentagemTaxa.Text);
                ms.MServico_Bulk_Porc_Imposto = Convert.ToDecimal(txtPorcentagemImposto1.Text);
                ms.MServico_Bulk_Porc_Comissao = Convert.ToDecimal(txtComissao.Text);
                ms.MServico_DataFrom = Convert.ToDateTime(from.Text);
                ms.MServico_DataTo = Convert.ToDateTime(to.Text);
                ms.MServico_Obs = txtObs.Text;
                ms.S_id = Convert.ToInt32(ViewState["IdSupplier"]);
                //ms.Tipo_Id = Convert.ToInt32(ddlTipoServico.SelectedValue);
                //ms.Tipo_categ_id = Convert.ToInt32(ddlTipoServicoCateg.SelectedValue);
                ms.ItemSubServico_id = Convert.ToInt32(ddlItemSubServico.SelectedValue);
                ms.SubItem_id = Convert.ToInt32(ddlSubItemSubServico.SelectedValue);

                msd.Salvar(ms);

                foreach (DataListItem item in DataListBases.Items)
                {
                    Monta_Servico_Valores msv = new Monta_Servico_Valores();

                    Label baseID = (Label)item.FindControl("baseID");
                    TextBox txtValoresBases = (TextBox)item.FindControl("txtValoresBases");
                    Label lblTotalBulk = (Label)item.FindControl("lblTotalBulk");
                    string Bulk = txtValoresBases.Text;

                    msv.IdMServico = ms.IdMServico;
                    msv.MServico_Valores_Bulk = Convert.ToDecimal(txtValoresBases.Text);

                    if (lblTotalBulk.Text.Equals(""))
                    { msv.MServico_Valores_Bulk_Total = null; }
                    else
                    { msv.MServico_Valores_Bulk_Total = Convert.ToDecimal(lblTotalBulk.Text); }

                    msv.Base_id = Convert.ToInt32(baseID.Text);

                    MontaServicoValoresDAL msvd = new MontaServicoValoresDAL();
                    msvd.Salvar(msv);
                }

                MostrarMsg("Registro cadastrado com sucesso.");

                //from.Text = "";
                //to.Text = "";
                txtObs.Text = "";

                popularDropSubItem();
                popularDropItemSubServico();

                rdoBasesIndex.SelectedValue = "1";

                PopulaDataListBases(1);

                PopulaGridMServicos();
            }
            catch (Exception ex)
            {
                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        protected void EditarMServico(object sender, CommandEventArgs e)
        {
            try
            {
                if ((base.ObterPerfilLogado() == (int)PerfilUsuario.Financeiro) ||
    (base.ObterPerfilLogado() == (int)PerfilUsuario.Operacional))
                    return;

                LimpaCampos(this.Controls);

                int myid = Convert.ToInt32(e.CommandArgument);

                MontaServicoDAL msd = new MontaServicoDAL();
                MontaServicoValoresDAL msvd = new MontaServicoValoresDAL();

                Monta_Servico ms = msd.ObterPorId(myid);

                txtCodMServico.Text = ms.IdMServico.ToString();
                txtSupplier.Text = ms.Supplier.S_nome;
                //ddlTipoServico.SelectedValue = ms.Tipo_Id.ToString();
                //popularDropTipoServicoCateg();
                //ddlTipoServicoCateg.SelectedValue = ms.Tipo_categ_id.ToString();
                from.Text = string.Format("{0:dd/MM/yyyy}", ms.MServico_DataFrom);
                to.Text = string.Format("{0:dd/MM/yyyy}", ms.MServico_DataTo);
                txtObs.Text = ms.MServico_Obs;
                txtPorcentagemTaxa.Text = ms.MServico_Bulk_Porc_Taxa.ToString();
                txtPorcentagemImposto1.Text = ms.MServico_Bulk_Porc_Imposto.ToString();
                txtComissao.Text = ms.MServico_Bulk_Porc_Comissao.ToString();
                ddlItemSubServico.SelectedValue = ms.ItemSubServico_id.ToString();
                ddlSubItemSubServico.SelectedValue = ms.SubItem_id.ToString();

                SBasesDAL bd = new SBasesDAL();

                S_Bases sb = bd.ObterPorIdSupplier(ms.S_id).First();

                ddlMercadoFiltro_Base.SelectedValue = sb.Mercado_id.ToString();
                ddlBaseTarifariaFiltro_Base.SelectedValue = sb.BaseTarifaria_id.ToString();
                ddlTipoBase_Base.SelectedValue = sb.TipoBase_id.ToString();
                ddlMoedaFiltro_Base.SelectedValue = sb.Moeda_id.ToString();

                Monta_Servico_Valores msv = msvd.ObterPorIdMServico(ms.IdMServico);

                int index = Convert.ToInt32(msv.S_Bases.Base_index);

                PopulaDataListBases(index);

                btnSalvarTarifas.Text = "Novo";
                btnAtualizarTarifas.Visible = true;
                lblMsgCadMServicos.Text = "";

                MostrarMsg("Navegue para aba List, para edição desse item selecionado.");

            }
            catch (Exception ex)
            {
                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        protected void AtualizarTarifas(object sender, EventArgs e)
        {
            try
            {
                Utils u = new Utils();
                MontaServicoDAL msd = new MontaServicoDAL();

                txtPorcentagemTaxa_TextChanged(sender, e);
                txtPorcentagemComissao_TextChanged(sender, e);

                if (ddlItemSubServico.SelectedValue.Equals("0"))
                { MostrarMsg("Favor selecione um item subserviço."); return; }
                if (ddlSubItemSubServico.SelectedValue.Equals("0"))
                { MostrarMsg("Favor selecione um sub item."); return; }

                foreach (DataListItem item in DataListBases.Items)
                {
                    TextBox txtValoresBases = (TextBox)item.FindControl("txtValoresBases");
                    string Bulk = txtValoresBases.Text;

                    if (!u.ValidaNumeroComVirgula(Bulk))
                    {
                        MostrarMsg("Favor digite somente números nas tarifas.");
                        return;
                    }
                }

                Monta_Servico ms = new Monta_Servico();

                ms.IdMServico = Convert.ToInt32(txtCodMServico.Text);
                ms.MServico_Bulk_Porc_Taxa = Convert.ToDecimal(txtPorcentagemTaxa.Text);
                ms.MServico_Bulk_Porc_Imposto = Convert.ToDecimal(txtPorcentagemImposto1.Text);
                ms.MServico_Bulk_Porc_Comissao = Convert.ToDecimal(txtComissao.Text);
                ms.MServico_DataFrom = Convert.ToDateTime(from.Text);
                ms.MServico_DataTo = Convert.ToDateTime(to.Text);
                ms.MServico_Obs = txtObs.Text;
                ms.S_id = Convert.ToInt32(ViewState["IdSupplier"]);
                //ms.Tipo_Id = Convert.ToInt32(ddlTipoServico.SelectedValue);
                //ms.Tipo_categ_id = Convert.ToInt32(ddlTipoServicoCateg.SelectedValue);
                ms.ItemSubServico_id = Convert.ToInt32(ddlItemSubServico.SelectedValue);
                ms.SubItem_id = Convert.ToInt32(ddlSubItemSubServico.SelectedValue);

                msd.Atualizar(ms);

                foreach (DataListItem item in DataListBases.Items)
                {
                    Monta_Servico_Valores msv = new Monta_Servico_Valores();

                    Label baseID = (Label)item.FindControl("baseID");
                    TextBox txtValoresBases = (TextBox)item.FindControl("txtValoresBases");
                    Label lblTotalBulk = (Label)item.FindControl("lblTotalBulk");
                    Label lblIDValores = (Label)item.FindControl("lblIDValores");

                    msv.IdMServicoValores = Convert.ToInt32(lblIDValores.Text);
                    msv.IdMServico = ms.IdMServico;
                    msv.MServico_Valores_Bulk = Convert.ToDecimal(txtValoresBases.Text);
                    msv.MServico_Valores_Bulk_Total = Convert.ToDecimal(lblTotalBulk.Text);
                    msv.Base_id = Convert.ToInt32(baseID.Text);

                    MontaServicoValoresDAL msvd = new MontaServicoValoresDAL();
                    msvd.Atualizar(msv);
                }

                MostrarMsg("Registro atualizado com sucesso.");
                PopulaGridMServicos();

            }
            catch (Exception ex)
            {
                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        protected void ExcluirMServico(object sender, CommandEventArgs e)
        {
            try
            {
                if ((base.ObterPerfilLogado() == (int)PerfilUsuario.Financeiro) ||
    (base.ObterPerfilLogado() == (int)PerfilUsuario.Operacional))
                    return;

                int myid = Convert.ToInt32(e.CommandArgument);

                MontaServicoDAL msd = new MontaServicoDAL();

                Monta_Servico ms = msd.ObterPorId(myid);

                msd.Excluir(ms);
                PopulaGridMServicos();
            }
            catch (Exception ex)
            {
                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        #endregion

        #region Regras

        [WebMethod]
        public static List<string> SearchSuppliers(string prefixText, int count)
        {
            try
            {
                SupplierDAL s = new SupplierDAL();

                List<Supplier> supp = s.ListarTodos(prefixText);

                List<string> lista = new List<string>();

                if (supp.Count == 0)
                {
                    lista.Add("Não existe supplier cadastrado com esse nome.");

                    return lista;
                }

                foreach (Supplier p in supp)
                {
                    lista.Add(p.S_nome);
                }

                return lista;
            }
            catch
            {
                throw;
            }
        }

        protected void VoltarMenu(object sender, EventArgs e)
        {
            Response.Redirect("~/Pages/Index.aspx");
        }

        protected void txtPorcentagemTaxa_TextChanged(object sender, EventArgs e)
        {

            Utils u = new Utils();

            if (!u.ValidaNumerosInteiros(txtPorcentagemImposto1.Text) || !u.ValidaNumerosInteiros(txtPorcentagemTaxa.Text))
            {
                MostrarMsg("Digite somente números inteiros nas taxas.");
                return;
            }
            else
            {
                lblMsgCadMServicos.Text = "";
            }

            PorcentagemTaxaDataList(DataListBases);

            //if (DataListBases2.Items.Count > 0)
            //{
            //    PorcentagemTaxaDataList(DataListBases2);
            //}

            //if (DataListBases3.Items.Count > 0)
            //{
            //    PorcentagemTaxaDataList(DataListBases3);
            //}

        }

        protected void txtPorcentagemComissao_TextChanged(object sender, EventArgs e)
        {

            Utils u = new Utils();

            if (!u.ValidaNumerosInteiros(txtComissao.Text))
            {
                MostrarMsg("Digite somente números inteiros na comissao.");
                return;
            }
            else
            {
                lblMsgCadMServicos.Text = "";
            }

            PorcentagemComissaoDataList(DataListBases);

            //if (DataListBases2.Items.Count > 0)
            //{
            //    PorcentagemComissaoDataList(DataListBases2);
            //}

            //if (DataListBases3.Items.Count > 0)
            //{
            //    PorcentagemComissaoDataList(DataListBases3);
            //}

        }

        protected void PorcentagemTaxaDataList(DataList nome)
        {
            try
            {

                foreach (DataListItem item in nome.Items)
                {
                    TextBox txtValoresBases = (TextBox)item.FindControl("txtValoresBases");
                    Label lblTotalBulk = (Label)item.FindControl("lblTotalBulk");
                    string Bulk = txtValoresBases.Text;

                    if (!Bulk.Equals(""))
                    {
                        if (!txtPorcentagemTaxa.Equals(""))
                        {
                            double valortarifa = Convert.ToDouble(Bulk);
                            double valortotalComTaxa = (valortarifa * Convert.ToDouble(txtPorcentagemTaxa.Text)) / 100;

                            double d = Convert.ToDouble(valortarifa + valortotalComTaxa);
                            Bulk = d.ToString("N2");

                            double valortarifa2 = Convert.ToDouble(Bulk);
                            double valortotalComImposto = (valortarifa2 * Convert.ToDouble(txtPorcentagemImposto1.Text)) / 100;

                            double d2 = Convert.ToDouble(valortarifa2 + valortotalComImposto);
                            lblTotalBulk.Text = d2.ToString("N2");
                        }
                        else
                        {
                            Bulk = "";
                        }
                    }
                    else
                    {
                        MostrarMsg("Favor digitar o valor do bulk antes das taxas.");
                        txtPorcentagemTaxa.Text = "0";
                        txtPorcentagemImposto1.Text = "0";
                    }
                }
            }
            catch (Exception ex)
            {
                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        protected void PorcentagemComissaoDataList(DataList nome)
        {
            Utils u = new Utils();

            foreach (DataListItem item in nome.Items)
            {
                TextBox txtValoresBases = (TextBox)item.FindControl("txtValoresBases");
                Label lblTotalBulk = (Label)item.FindControl("lblTotalBulk");
                string Bulk = txtValoresBases.Text;

                if (!Bulk.Equals(""))
                {
                    if (!txtComissao.Equals(""))
                    {
                        //PorcentagemTaxaDataList(nome);

                        double valortarifa = Convert.ToDouble(Bulk);
                        double valortotalComComissao = (valortarifa * Convert.ToDouble(txtComissao.Text)) / 100;

                        double d = Convert.ToDouble(Convert.ToDouble(lblTotalBulk.Text) - valortotalComComissao);
                        lblTotalBulk.Text = d.ToString("N2");
                    }
                }
                else
                {
                    MostrarMsg("Favor digitar o valor do bulk antes das taxas.");
                }
            }

        }

        protected void Limpar(object sender, EventArgs e)
        {
            LimpaCampos(this.Controls);
        }

        protected void LimpaCampos(ControlCollection controls)
        {
            foreach (Control ctrl in controls)
            {
                if (ctrl is TextBox)
                {
                    (ctrl as TextBox).Text = string.Empty;
                }
                // ... demais controles que queira limpar

                LimpaCampos(ctrl.Controls);
            }
        }

        protected void LimparTextos()
        {
            txtObs.Text = "";
        }

        protected void PreencheDataListBase(object sender, EventArgs e)
        {
            PopulaDataListBases(Convert.ToInt32(rdoBasesIndex.SelectedValue));
            PopulaGridMServicos();
            lblMsgCadMServicos.Text = "";
            from.Text = "";
            to.Text = "";
            PanelDataLists.Visible = true;
        }

        protected void MontaDataListBases(object sender, EventArgs e)
        {
            PopulaDataListBases(Convert.ToInt32(rdoBasesIndex.SelectedValue));
        }

        protected void ddlMercadoFiltro_Base_SelectedIndexChanged(object sender, EventArgs e)
        {
            PopulaDataListBases(Convert.ToInt32(rdoBasesIndex.SelectedValue));
        }

        protected void ddlBaseTarifariaFiltro_Base_SelectedIndexChanged(object sender, EventArgs e)
        {
            PopulaDataListBases(Convert.ToInt32(rdoBasesIndex.SelectedValue));
        }

        protected void ddlMoedaFiltro_Base_SelectedIndexChanged(object sender, EventArgs e)
        {
            PopulaDataListBases(Convert.ToInt32(rdoBasesIndex.SelectedValue));
        }

        protected void ddlTipoTransporte_SelectedIndexChanged(object sender, EventArgs e)
        {
            PopulaDataListBases(Convert.ToInt32(rdoBasesIndex.SelectedValue));
        }

        protected void ddlTipoBase_Base_SelectedIndexChanged(object sender, EventArgs e)
        {
            PopulaDataListBases(Convert.ToInt32(rdoBasesIndex.SelectedValue));
        }

        protected void btnImgAtualizarTaxas_Click(object sender, ImageClickEventArgs e)
        {
            txtPorcentagemTaxa_TextChanged(sender, e);
            txtPorcentagemComissao_TextChanged(sender, e);
        }

        protected void btnCopiarDividir_Click(object sender, EventArgs e)
        {
            try
            {

                if (RdoDividir.SelectedValue.Equals(""))
                {
                    MostrarMsg("Favor selecionar a opção de divisão.");
                }
                else
                {
                    MontarValores(RdoDividir.SelectedValue);
                }

            }
            catch (Exception ex)
            {
                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        protected void MontarValores(string op)
        {
            try
            {

                foreach (DataListItem item in DataListBases.Items)
                {
                    Label baseDe = (Label)item.FindControl("baseDe");
                    TextBox txtValoresBases = (TextBox)item.FindControl("txtValoresBases");

                    if (Convert.ToInt32(baseDe.Text) > Convert.ToInt32(txtParaDividir.Text))
                    {
                        break;
                    }

                    if (op.Equals("S") && Convert.ToInt32(baseDe.Text) >= Convert.ToInt32(txtDeDividir.Text))
                    {
                        decimal divisao = Convert.ToDecimal(txtValorDividir.Text) / Convert.ToDecimal(baseDe.Text);
                        txtValoresBases.Text = divisao.ToString("N2");
                    }
                    else if (Convert.ToInt32(baseDe.Text) >= Convert.ToInt32(txtDeDividir.Text))
                    {
                        txtValoresBases.Text = txtValorDividir.Text;
                    }
                }

            }
            catch (Exception ex)
            {
                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        protected void rdoBasesIndex_SelectedIndexChanged(object sender, EventArgs e)
        {
            PopulaDataListBases(Convert.ToInt32(rdoBasesIndex.SelectedValue));
        }

        protected void btnFiltroMServico_Click(object sender, ImageClickEventArgs e)
        {
            try
            {

                if (txtFiltroMServicosDataFrom.Text.Equals("") || txtFiltroMServicosDataTo.Text.Equals(""))
                {
                    MostrarMsg("Favor preencher as datas para filtrar.");
                    return;
                }

                MontaServicoDAL ms = new MontaServicoDAL();

                GridMServicos.DataSource = ms.ListarTodosCondicaoMSCustos(Convert.ToInt32(ViewState["IdSupplier"]), Convert.ToDateTime(txtFiltroMServicosDataFrom.Text), Convert.ToDateTime(txtFiltroMServicosDataTo.Text), Convert.ToInt32(ddlFiltroMServicoItemSubServico.SelectedValue), Convert.ToInt32(ddlFiltroMServicoSubItem.SelectedValue), Convert.ToInt32(rdoBasesIndexSubServico.SelectedValue));
                GridMServicos.DataBind();

            }
            catch (Exception ex)
            {
                MostrarMsg(ex.Message);
            }
        }

        protected void txtValoresBases_TextChanged(object sender, EventArgs e)
        {

            TextBox txt = (TextBox)sender;
            string commandArg = txt.Attributes["CommandArgument"].ToString();
            //String commandName = txt.Attributes["CommandName"].ToString();

            foreach (DataListItem item in DataListBases.Items)
            {
                TextBox txtValoresBases = (TextBox)item.FindControl("txtValoresBases");
                Label lblTotalBulk = (Label)item.FindControl("lblTotalBulk");
                Label baseID = (Label)item.FindControl("baseID");
                string Bulk = txtValoresBases.Text;

                if (Convert.ToInt32(commandArg) == item.ItemIndex)
                {
                    if (chkPercentValorSS.Checked)
                    {
                        double soma = Convert.ToDouble(txtValoresBases.Text);

                        soma = soma + Convert.ToDouble(txtValorAdicional.Text);

                        txtValoresBases.Text = soma.ToString("N2");

                        if (!txtPercentValorAdicional.Text.Equals(""))
                        {
                            double percentAdicional = (soma * Convert.ToDouble(txtPercentValorAdicional.Text) / 100) + soma;

                            txtValoresBases.Text = percentAdicional.ToString("N2");
                        }
                    }
                }

                if (item.ItemIndex == Convert.ToInt32(commandArg) + 1)
                {
                    txtValoresBases.Focus();
                }

            }
        }

        protected void chkPercentValorSS_CheckedChanged(object sender, EventArgs e)
        {
            if (chkPercentValorSS.Checked)
            {
                OpenCalc.ImageUrl = "../../images/Icones/calc2.png";
            }
            else
            {
                OpenCalc.ImageUrl = "../../images/Icones/calc2S.png";
            }

            ModalPopupExtenderAddCategoria.Show();
        }

        #endregion

        protected void MostrarMsg(string Msg)
        {
            ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "call me", "showAutoCloseMessage('" + Msg + "')", true);
        }



    }
}